import {
  getSaleAnalysisTable
} from '../../api/sale'
import {
  SALE_ANALYSIS_LIST,
  SALE_ANALYSIS_CURRENT_ROW,
  SALE_ANALYSIS_DATA_COUNT,
  SALE_ANALYSIS_HISTORY_DATA,
  SALE_ANALYSIS_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    saleAnalysisList: [],
    saleAnalysisDataCount: null,
    saleAnalysisPageSize: 20,
    saleAnalysisHistoryData: [],
    row: {
      ctime: '',
      uname: '',
      cstnum: '',
      lostnum: '',
      allnum: '',
      yxrate: '',
      lostrate: '',
      avgtime: '',
      salemoney: ''
    }
  },
  getters: {
    saleAnalysisList: state => state.saleAnalysisList
  },
  mutations: {
    [SALE_ANALYSIS_LIST] (state, data) {
      state.saleAnalysisList = data
    },
    [SALE_ANALYSIS_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [SALE_ANALYSIS_DATA_COUNT] (state, data) {
      state.saleAnalysisDataCount = data
    },
    [SALE_ANALYSIS_HISTORY_DATA] (state, data) {
      state.saleAnalysisHistoryData = data
    },
    [SALE_ANALYSIS_PAGE_SIZE] (state, data) {
      state.saleAnalysisPageSize = data
    }
  },
  actions: {
    async getSaleAnalysisList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getSaleAnalysisTable(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          ctime: item.ctime,
          uname: item.uname,
          cstnum: item.cstnum,
          lostnum: item.lostnum,
          allnum: item.allnum,
          yxrate: item.yxrate,
          lostrate: item.lostrate,
          avgtime: item.avgtime,
          salemoney: item.salemoney
        }]
      })
      commit(SALE_ANALYSIS_LIST, newData)
      commit(SALE_ANALYSIS_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.saleAnalysis.saleAnalysisPageSize) {
        commit(SALE_ANALYSIS_HISTORY_DATA, newData)
      } else {
        commit(SALE_ANALYSIS_HISTORY_DATA, newData.slice(0, rootState.saleAnalysis.saleAnalysisPageSize))
      }
      return resp
    },
    async getSaleAnalysisCurrentRow ({ commit, rootState }, row) {
      commit(SALE_ANALYSIS_CURRENT_ROW, row)
    },
    async changeSaleAnalysisPage ({ commit, rootState }, index) {
      let data = rootState.saleAnalysis.saleAnalysisList
      let _start = (index - 1) * rootState.saleAnalysis.saleAnalysisPageSize
      let _end = index * rootState.saleAnalysis.saleAnalysisPageSize
      commit(SALE_ANALYSIS_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeSaleAnalysisPageSize ({ commit, rootState }, value) {
      commit(SALE_ANALYSIS_PAGE_SIZE, value)
    }
  }
}
